<?php

namespace App\Http\Controllers;

use App\Http\Model\DocumentsContent;
use Illuminate\Http\Request;
use App\Http\Model\Documents as DocumentsModel;
use App\Http\Model\DocumentsContent as DocmnentsContentModel;
use App\Http\Model\Configs as ConfigsModel;
use Illuminate\Support\Facades\DB;


class AdminController extends Controller
{
    protected $request;
    protected $documentsModel;

    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request        = $request;
        $this->documentsModel = new DocumentsModel();
    }

    /**
     * 首页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {

        $assign = ['title' => '首页'];
        return view('admin.index', $assign);
    }

    /**
     * 文档列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function document()
    {
        $p = $this->request->input('p', 1);

        //获取url参数，排除掉p
        $url_params     = $this->request->except('p');
        $url_params_str = '';
        foreach ($url_params as $key => $val) {
            $url_params_str .= $key . '=' . $val . '&';
        }

        $condition = [];

        if ($this->request->has('file_name') && $this->request->input('file_name')) {
            $condition['file_name'] = $this->request->input('file_name');
        }

        if ($this->request->has('title') && $this->request->input('title')) {
            $condition['title'] = $this->request->input('title');
        }

        if ($this->request->has('keyword') && $this->request->input('keyword')) {
            $condition['keyword'] = $this->request->input('keyword');
        }

        $count = $this->documentsModel->where(function ($query) use ($condition) {
            isset($condition['file_name']) && $query->where('file_name', 'like', "%{$condition['file_name']}%");
            isset($condition['title']) && $query->where('title', 'like', "%{$condition['title']}%");
            isset($condition['keyword']) && $query->where('keyword', 'like', "%{$condition['keyword']}%");
        })->count();

        $limit  = 15;
        $offset = ($p - 1) * $limit;
        $list   = $this->documentsModel->where(function ($query) use ($condition) {
            isset($condition['file_name']) && $query->where('file_name', 'like', "%{$condition['file_name']}%");
            isset($condition['title']) && $query->where('title', 'like', "%{$condition['title']}%");
            isset($condition['keyword']) && $query->where('keyword', 'like', "%{$condition['keyword']}%");

        })->limit($limit)->offset($offset)->get()->toArray();
        //dd($list);

        $assign = [
            'title'         => '文档管理',
            'list'          => $list,
            'count'         => $count,
            'limit'         => $limit,
            'p'             => $p,
            'url_param_str' => trim($url_params_str, '&')
        ];
        //dump($assign);
        return view('admin.document', $assign);
    }

    /**
     * 编辑保存文档
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function document_edit()
    {
        $id = $this->request->input('id');

        if ($this->request->isMethod('post')) {
            try {
                DB::beginTransaction();

                $params = $this->request->all();
                $data   = [
                    'file_name'   => $params['file_name'],
                    'title'       => $params['title'],
                    'keyword'     => $params['keyword'],
                    'update_time' => date('Y-m-d H:i:s')
                ];
                $res    = $this->documentsModel->where('id', $params['id'])->update($data);
                if ($res === false) {
                    throw new \Exception('保存主表失败！');
                }

                $res = DocmnentsContentModel::where('id', $params['id'])->update(['content'=>$params['content']]);
                if ($res === false) {
                    throw new \Exception('保存内容表失败！');
                }

                DB::commit();
                return ['code' => 1, 'msg' => '保存成功！'];
            } catch (\Exception $e) {
                DB::rollBack();
                return ['code' => 0, 'msg' => $e->getMessage()];
            }
        }

        $info = $this->documentsModel->where('id', '=', $id)->first();
        $contentArr = $info->getContent;
        $info->content = $contentArr['content'];
        $info = $info->toArray();
        //dd($info);
        $assign = [
            'title' => '编辑文档',
            'info'  => $info
        ];
        return view('admin.document_edit', $assign);
    }

    /**
     * 统计
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function statistics()
    {

        $assign = [];
        return view('admin.statistics', $assign);
    }

    /**
     * 设置
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function setups()
    {
        $configsModel = new ConfigsModel();

        if ($this->request->isMethod('post')) {
            $params = $this->request->all();
            $data = [
                'web_name'=>$params['web_name'],
                'web_url'=>$params['web_url'],
                'version'=>$params['version'],
                'last_update_time'=>$params['last_update_time']
            ];
            $res = $configsModel->where('id', $params['id'])->update($data);
            if (!$res) {
                return ['code' => 0, 'msg' => '保存失败！'];
            }
            return ['code' => 1, 'msg' => '保存成功！'];
        }

        $info = $configsModel->first();

        $assign = [
            'title'=>'设置',
            'info'=>$info
        ];
        return view('admin.setups', $assign);
    }
}
